var express = require('express');
var router = express.Router();

const mongoose = require('mongoose');

const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({
    extended: false
});

const bcrypt = require('bcrypt');

const passport = require('../../../config/auth.config');

/**
 * 引入模型
 * @type models
 */
const User = require('../../models/User');

/* GET users listing. */
router.get('/', async ctx => {
    await ctx.res.send({
        code: 200,
        data: {
            name: 'tom'
        },
        msg: 'users请求成功！'
    });
});
router.get('/register', async ctx => {
    await ctx.res.render('users/register');
});
router.post('/register', async ctx => {
    let errors = [];
    if (ctx.body.password.length < 4) {
        errors.push({
            text: '密码长度不能小于4！'
        })
    }
    if (errors.length > 0) {
        ctx.res.render('users/register', {
            errors,
            name: ctx.body.name,
            email: ctx.body.email,
            password: ctx.body.password
        })
    } else {
        let user = await User.findOne({
            email: ctx.body.email
        })
        if (user) {
            ctx.flash('error_msg', '邮箱已存在，请更换邮箱注册！');
            ctx.res.redirect('/users/register');
        } else {
            let newUser = new User({
                name: ctx.body.name,
                email: ctx.body.email,
                password: ctx.body.password,
            })

            bcrypt.genSalt(10, (err, salt) => { //密码强度，回调函数
                bcrypt.hash(newUser.password, salt, async (err, hash) => { //需要加密项，回调函数
                    if (err) throw err;
                    newUser.password = hash; //保存加密结果
                    try {
                        await newUser.save();
                        ctx.flash('success_msg', '账号注册成功！');
                        ctx.res.redirect('/users/login');
                    } catch (e) {
                        ctx.flash('success_msg', '账号注册失败！');
                        ctx.res.redirect('/users/register');
                    }
                })
            })
        }
    }
});

router.get('/login', async ctx => {
    await ctx.res.render('users/login');
});
router.put('/login', async ctx => {
    passport.authenticate('local', (user, info) => {
        if(user) {
            ctx.logIn(user, err => {
                ctx.flash('success_msg', '登录成功！');
                ctx.res.redirect('/ideas/list')
            })

        }else{
            ctx.flash('error_msg', info.message);
            ctx.res.redirect('/users/login')
        }
    })(ctx)
});

router.get('/logout', ctx => {
    ctx.logOut();
    ctx.flash('success_msg', '退出成功！');
    ctx.res.redirect('/users/login');
})

module.exports = router;
